import fs from 'fs';
import lessToJS from 'less-vars-to-js';
import path from 'path';
import { clean } from '@open-tech-world/rollup-plugin-clean';
import { viteStaticCopy } from 'vite-plugin-static-copy';

import { defineConfig } from 'vite';

import react from '@vitejs/plugin-react';

export default defineConfig(({ command, mode }) => {
  if (mode === 'lib') {
    return {
      build: {
        outDir: 'lib',
        lib: {
          entry: path.resolve(__dirname, 'iframe.ts'),
          name: 'iframe',
          // the proper extensions will be added
          fileName: 'iframe',
        },
      },
    };
  }

  return {
    resolve: {
      alias: [
        { find: /^~/, replacement: '' },
        { find: /^@(?=\/)/, replacement: path.resolve(__dirname, './src') },
      ],
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {},
          javascriptEnabled: true,
        },
      },
    },
    plugins: [
      react(),
      viteStaticCopy({
        targets: [
          {
            src: './iframe.mjs',
            dest: '.',
          },
        ],
      }),
    ],
    build: {
      rollupOptions: {
        plugins: [
          // 删除 __pycache__，减小打包大小
          clean(['**/__pycache__']),
        ],
      },
    },
  };
});
